package com.lg.happyfarmer.base;

import android.Manifest;
import android.R;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.UnderlineSpan;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.lg.happyfarmer.activity.LoginActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import xtom.frame.XtomActivityManager;
import xtom.frame.util.XtomBaseUtil;
import xtom.frame.util.XtomFileUtil;
import xtom.frame.util.XtomSharedPreferencesUtil;
import xtom.frame.util.XtomTimeUtil;

/**
 * 工具类
 */
public class BaseUtil {

/**
 * 加载动画
 */

public static void startLayoutAnim(Context mContext,LinearLayout ll_all) {
    //通过加载XML动画设置文件来创建一个Animation对象；
    Animation animation = AnimationUtils.loadAnimation(mContext, com.lg.happyfarmer.R.anim.slide_right);
    //得到一个LayoutAnimationController对象；
    LayoutAnimationController lac = new LayoutAnimationController(animation);
    //设置控件显示的顺序；
    lac.setOrder(LayoutAnimationController.ORDER_NORMAL);
    //设置控件显示间隔时间；
    lac.setDelay(1);
    //为ListView设置LayoutAnimationController属性；
    ll_all.setLayoutAnimation(lac);
}

    /**
     * 常用手机号的判断
     */
    public static boolean isMobileNO(String mobiles) {
        boolean flag = false;
        try {
            Pattern p = Pattern.compile("^[1][3,4,5,8][0-9]{9}$"); // 验证手机号
            Matcher m = p.matcher(mobiles);
            flag = m.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }
    private static double EARTH_RADIUS = 6378.137;// 地球半径
//    public static final SHARE_MEDIA[] shareList = new SHARE_MEDIA[]
//            {
//                    SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE
//            };

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * 根据手机分辨率从dp转成px
     *
     * @param context
     * @param dpValue
     * @return
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static String transDuration(long duration) {
        String ds = "";
        long min = duration / 60;
        if (min < 60) {
            ds += (min + "分钟");
        } else {
            long hour = min / 60;
            long rm = min % 60;
            if (rm > 0)
                ds += (hour + "小时" + rm + "分钟");
            else
                ds += (hour + "小时");
        }
        return ds;
    }

    public static String transDistance(float distance) {
        String ds = "";
        if (distance < 1000) {
            ds += (distance + "米");
        } else {
            float km = distance / 1000;
            ds += (String.format(Locale.getDefault(), "%.2f", km) + "千米");
        }
        return ds;
    }

    /**
     * 计算两点间的距离
     *
     * @param lat1
     * @param lng1
     * @param lat2
     * @param lng2
     * @return
     */
    public static Double GetDistance(double lat1, double lng1, double lat2,
                                     double lng2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);

        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return s;
    }

    /**
     * 隐藏用户名
     *
     * @param nickname
     * @return
     */
    public static String hideNickname(String nickname) {
        int length = nickname.length();
        String first = nickname.substring(0, 3);
        String last = nickname.substring(length - 3, length);
        String x = "";
        for (int i = 0; i < length - 6; i++) {
            x += "*";
        }
        return first + x + last;
    }

    /**
     * 是否已经登录
     *
     * @return
     */
    public static boolean isLogin() {
        if (BaseApplication.getInstance().getUser() == null) {
            return false;
        } else {
            return true;
        }
    }

    public static void checkLogin(Context mContext) {
        Intent it = new Intent(mContext, LoginActivity.class);
        mContext.startActivity(it);
    }

    ;

    public static void exit(Context context) {
        XtomActivityManager.finishAll();
    }


    /**
     * 功能描述：[是否早于当前时间]
     * 程序作者：WZL
     * 编写时间：[2015年4月9日]-[下午3:44:49]
     *
     * @param endtime
     * @return true 早 false 晚
     */
    public static boolean isBefore(String endtime) {
        Date nowDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
                Locale.getDefault());
        try {
            Date endDate = sdf.parse(endtime);
            return nowDate.before(endDate);
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 功能描述：[重置listview高度]
     * 程序作者：WZL
     * 编写时间：[2015年4月9日]-[下午9:11:43]
     *
     * @param listView
     */
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition  
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    /**
     * 重新计算listView的高度
     *
     * @param listView
     */
    public static int setListViewHeightBasedOnChildren(ListView listView, int moreHeight, Context context) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition  
            return 0;
        }

        int totalHeight = 0;
        if (listAdapter.getCount() > 0) {
            for (int i = 0; i < listAdapter.getCount(); i++) {
                View listItem = listAdapter.getView(i, null, listView);
                listItem.measure(0, 0);
                totalHeight += listItem.getMeasuredHeight();
            }
        }
        moreHeight = dip2px(context, moreHeight);
        totalHeight += moreHeight;
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
        return params.height;

    }

    /**
     * 将日期转换为制定的时间格式的字符串
     *
     * @param date
     * @param format
     * @return
     */
    public static String transString(Date date, SimpleDateFormat format) {
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String str = format.format(date);
        return str;
    }

    /**
     * 转换时间显示形式(与当前系统时间比较),在显示即时聊天的时间时使用
     *
     * @param time 时间字符串
     * @return String
     */
    public static String transTimeChat(String time) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
                    Locale.getDefault());
            String current = XtomTimeUtil.getCurrentTime("yyyy-MM-dd HH:mm:ss");
            String dian24 = XtomTimeUtil.TransTime(current, "yyyy-MM-dd")
                    + " 24:00:00";
            String dian00 = XtomTimeUtil.TransTime(current, "yyyy-MM-dd")
                    + " 00:00:00";
            Date now = null;
            Date date = null;
            Date d24 = null;
            Date d00 = null;
            try {
                now = sdf.parse(current); // 将当前时间转化为日期
                date = sdf.parse(time); // 将传入的时间参数转化为日期
                d24 = sdf.parse(dian24);
                d00 = sdf.parse(dian00);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            long diff = now.getTime() - date.getTime(); // 获取二者之间的时间差值
            long min = diff / (60 * 1000);
            if (min <= 5)//5分钟之内
                return "刚刚";
            if (min < 60)//1个小时之内
                return min + "分钟前";

            if (now.getTime() <= d24.getTime()
                    && date.getTime() >= d00.getTime())
                return "今天" + XtomTimeUtil.TransTime(time, "HH:mm");

            int sendYear = Integer
                    .valueOf(XtomTimeUtil.TransTime(time, "yyyy"));
            int nowYear = Integer.valueOf(XtomTimeUtil.TransTime(current,
                    "yyyy"));
            if (sendYear < nowYear)
                return XtomTimeUtil.TransTime(time, "yyyy-MM-dd HH:mm");
            else
                return XtomTimeUtil.TransTime(time, "MM-dd HH:mm");
        } catch (Exception e) {
            return null;
        }

    }

    // 获取软件Logo文件地址
    public static String getLogoImagePath(Context context) {
        String imagePath;
        try {
            String cachePath_internal = XtomFileUtil.getCacheDir(context)
                    + "/images/";// 获取缓存路径
            File dirFile = new File(cachePath_internal);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            imagePath = cachePath_internal + "icon.png";
            File file = new File(imagePath);
            if (!file.exists()) {
                file.createNewFile();
                Bitmap pic = BitmapFactory.decodeResource(
                        context.getResources(), R.mipmap.sym_def_app_icon);
                FileOutputStream fos = new FileOutputStream(file);
                pic.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.flush();
                fos.close();
            }
        } catch (Throwable t) {
            t.printStackTrace();
            imagePath = null;
        }
        return imagePath;
    }

//	public final static DisplayImageOptions avatarImageOptions  = new DisplayImageOptions.Builder()
//			.showImageOnLoading(R.drawable.default_rabbit_grey)
//			.showImageOnFail(R.drawable.default_rabbit_grey)
//			.cacheInMemory(true)
//			.cacheOnDisk(true)
//			.bitmapConfig(Bitmap.Config.RGB_565)
//			.build();
//
//	public final static DisplayImageOptions smallImageOptions  = new DisplayImageOptions.Builder()
//			.showImageOnLoading(R.drawable.no_pic_small)
//			.showImageOnFail(R.drawable.no_pic_small)
//			.showImageForEmptyUri(R.drawable.no_pic_small)
//			.cacheInMemory(true)
//			.cacheOnDisk(true)
//			.bitmapConfig(Bitmap.Config.RGB_565)
//			.build();
//
//    public final static DisplayImageOptions midImageOptions  = new DisplayImageOptions.Builder()
//            .showImageOnLoading(R.drawable.no_pic_mid)
//            .showImageOnFail(R.drawable.no_pic_mid)
//			.showImageForEmptyUri(R.drawable.no_pic_mid)
//            .cacheInMemory(true)
//            .cacheOnDisk(true)
//            .bitmapConfig(Bitmap.Config.RGB_565)
//            .build();
//
//    public final static DisplayImageOptions bigImageOptions  = new DisplayImageOptions.Builder()
//            .showImageOnLoading(R.drawable.no_pic_big)
//            .showImageOnFail(R.drawable.no_pic_big)
//			.showImageForEmptyUri(R.drawable.no_pic_big)
//            .cacheInMemory(true)
//            .cacheOnDisk(true)
//            .bitmapConfig(Bitmap.Config.RGB_565)
//            .build();
//
//	public final static DisplayImageOptions circleAvatarOptions  = new DisplayImageOptions.Builder()
//			.showImageOnLoading(R.drawable.default_rabbit_grey)
//			.showImageOnFail(R.drawable.default_rabbit_grey)
//			.showImageForEmptyUri(R.drawable.default_rabbit_grey)
//			.cacheInMemory(true)
//			.cacheOnDisk(true)
//			.bitmapConfig(Bitmap.Config.RGB_565)
//			.displayer(new CircleBitmapDisplayer(0))
//			.build();



    /**
     * 由商品详情类型type 获取 该商品商品商家列表keytype类型
     *
     * @param type
     * @return
     */
    public static String getKeytypeByBlogType(String type) {
        String keytype = "";
        switch (type) {
            case "1":
                keytype = "3";
                break;
            case "2":
                keytype = "2";
                break;
            case "3":
                keytype = "4";
                break;
            case "4":
                break;
            case "5":
                keytype = "7";
                break;
            case "6":
                keytype = "11";
                break;
            case "9":
                break;
            case "11":
                keytype = "16";
                break;
            case "12":
                keytype = "24";
                break;
            case "13":
                keytype = "19";
                break;
            case "14":
                keytype = "20";
                break;
            case "21":
                keytype = "17";
                break;
            case "15":
            case "16":
                keytype = "21";
                break;
            default:
                keytype = "18";
                break;
        }
        return keytype;
    }

    /**
     * Keytype 转换（我的关注）
     *
     * @param type
     * @return
     */
    public static String getMerchantKeytype(String type) {
        String keytype = "";
        switch (type) {
            case "3":
                keytype = "3";
                break;
            case "11":
                keytype = "4";
                break;
            case "14":
                keytype = "11";
                break;
            case "15":
                keytype = "16";
                break;
            case "18":
                keytype = "17";
                break;
            case "24":
                keytype = "19";
                break;
            case "25":
                keytype = "20";
                break;
            case "26":
            case "27":
                keytype = "21";
                break;
            default:
                keytype = "18";
                break;
        }
        return keytype;
    }

    /**
     * 获取keyid 无 or 0(仅针对商家店铺处理)
     *
     * @param keytype
     * @return
     */
    public static String getKeyId(String keytype) {
        String keyid = "";
        switch (keytype) {
            case "8":
            case "18":
            case "3":
                keyid = "0";
                break;
            case "2":
            case "16":
            case "17":
            case "19":
            case "20":
            case "21":
            case "23":
            case "24":
            case "11":
                keyid = "无";
                break;
            default:
                keyid = "0";
                break;
        }
        return keyid;
    }

    /**
     * 判断是否是第一次登录
     *
     * @param context
     * @return true是第一次，false不是第一次
     */
    public static boolean checkVirgin(Context context) {
        String isVirgin = XtomSharedPreferencesUtil.get(context, "isVirgin");
        boolean virgin = "false".equals(isVirgin);//非false，全部认为是第一次
        if (!virgin)//如果是第一次，就将其置为false
            XtomSharedPreferencesUtil.save(context, "isVirgin", "false");
        return !virgin;
    }

    /**
     * 检测版本变化（版本变化时，重新加载引导页 重新弹框）
     *
     * @param mContext
     * @param flag     GUIDE 引导页 INDEX首页
     * @return
     */
    public static boolean checkVersionChange(Context mContext, String flag) {
        try {
            String oldVersion = XtomSharedPreferencesUtil.get(mContext, "version" + flag);
            String curVersion = XtomBaseUtil.getAppVersionName(mContext);
            if (!curVersion.equals(oldVersion)) {
                XtomSharedPreferencesUtil.save(mContext, "version" + flag, curVersion);
                return true;
            } else {
                return false;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static String transNull(String content) {
        if (content == null || content.equals("null"))
            content = "";
        return content;
    }

    /**
     * 在TextView显示的内容中，插入粮票符号
     *
     * @param textView 要显示的TextView
     * @param stampId  粮票的图片资源id
     */
    public static void addStampSign(Context context, TextView textView, int stampId) {
        final SpannableString ss = new SpannableString("stamp");
        Drawable d = context.getResources().getDrawable(stampId);
        d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
        ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
        ss.setSpan(span, 0, "stamp".length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        textView.append(ss);
    }

    /**
     * 给Edittext加入emoji的过滤，禁止输入emoji
     * 同时最多输入20个字符
     *
     * @param et
     */
    public static void setEmojiFilter(EditText et) {
        InputFilter emojiFilter = new InputFilter() {
            Pattern pattern = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]", Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);

            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                Matcher matcher = pattern.matcher(source);
                if (matcher.find()) {
                    return "";
                }
                return null;
            }
        };
        InputFilter lengthFilter = new InputFilter.LengthFilter(20);
        et.setFilters(new InputFilter[]{emojiFilter, lengthFilter});
    }

    /**
     * 限制Emoji 并指定最大长度
     *
     * @param et
     * @param length
     */
    public static void setEmojiFilterWithLength(EditText et, int length) {
        InputFilter emojiFilter = new InputFilter() {
            Pattern pattern = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]", Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);

            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                Matcher matcher = pattern.matcher(source);
                if (matcher.find()) {
                    return "";
                }
                return null;
            }
        };
        InputFilter lengthFilter = new InputFilter.LengthFilter(length);
        et.setFilters(new InputFilter[]{emojiFilter, lengthFilter});
    }

    /**
     * 限制Emoji
     *
     * @param et
     */
    public static void setEmojiFilterWithOutLength(EditText et) {
        InputFilter emojiFilter = new InputFilter() {
            Pattern pattern = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]", Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);

            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                Matcher matcher = pattern.matcher(source);
                if (matcher.find()) {
                    return "";
                }
                return null;
            }
        };
        et.setFilters(new InputFilter[]{emojiFilter});
    }

    public static void initWebview(WebView webView) {
        // 支持javascript
        webView.getSettings().setJavaScriptEnabled(true);
        // 设置可以支持缩放
        webView.getSettings().setSupportZoom(true);
        // 设置出现缩放工具
        webView.getSettings().setBuiltInZoomControls(true);
        // 扩大比例的缩放
        webView.getSettings().setUseWideViewPort(true);
        // 自适应屏幕
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setLoadWithOverviewMode(true);
        // 取消显示滚动条
        webView.setVerticalScrollBarEnabled(false);
        webView.setHorizontalScrollBarEnabled(false);

        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });

        webView.getSettings().setSavePassword(true);
        webView.getSettings().setSaveFormData(true);
        webView.getSettings().setGeolocationEnabled(true);
        webView.getSettings().setGeolocationDatabasePath("/data/data/org.itri.html5webView/databases/");     // enable Web Storage: localStorage, sessionStorage
        webView.getSettings().setDomStorageEnabled(true);
        webView.requestFocus();
//        webView.setScrollBarStyle(0);
    }

    public static boolean checkCameraPermission(@NonNull Context context) {
        int permission = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
        return permission == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * 判断聊天界面是否正在运行
     *
     * @param context
     * @return
     */
    public static boolean isChatRunning(Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> mRunningTasks = manager.getRunningTasks(1);
        ActivityManager.RunningTaskInfo runningTaskInfo = mRunningTasks.get(0);
        if (runningTaskInfo != null) {
            return TextUtils.equals(runningTaskInfo.topActivity.getClassName(), "com.hemaapp.yjnh.chat.ChatPrivateActivity");
        }
        return false;
    }

    /**
     * 获取屏幕宽度
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        // 取得窗口属性
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        // 窗口的宽度
        return wm.getDefaultDisplay().getWidth();
    }

    /**
     * 获取屏幕高度
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        // 取得窗口属性
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        // 窗口的宽度
        return wm.getDefaultDisplay().getHeight();
    }

    /**
     * 添加删除线
     *
     * @param view
     * @param msg
     */
    public static void setThroughSpan(TextView view, String msg) {
        if (msg.length() > 0) {
            SpannableString ss = new SpannableString(msg);
            StrikethroughSpan span = new StrikethroughSpan();
            ss.setSpan(span, 0, msg.length(),
                    SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
            view.setText(ss);
        }
    }

    /**
     * 设置下划线
     *
     * @param view
     * @param msg
     */
    public static void setUnderlineSpan(TextView view, String msg) {
        if (msg.length() > 0) {
            SpannableString ss = new SpannableString(msg);
            UnderlineSpan span = new UnderlineSpan();
            ss.setSpan(span, 0, msg.length(),
                    SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
            view.setText(ss);
        }
    }

    /**
     * 设置TextView中字体颜色（转账需扣除2%的手续费）
     *
     * @param view
     * @param msg
     */
    public static void setForegroundColorSpan(TextView view, String msg, int start, int end) {
        if (msg.length() > 0) {
            SpannableString ss = new SpannableString(msg);
            ForegroundColorSpan span = new ForegroundColorSpan(Color.parseColor("#ea361c"));
            ss.setSpan(span, start, end,
                    SpannableString.SPAN_INCLUSIVE_INCLUSIVE);
            view.setText(ss);
        }
    }

    /**
     * 设置TextView中字体颜色
     *
     * @param view
     * @param msg
     * @param start
     * @param end
     * @param color #ea361c
     */
    public static void setForegroundColorSpan(TextView view, String msg, int start, int end, String color) {
        if (msg.length() > 0) {
            SpannableString ss = new SpannableString(msg);
            ForegroundColorSpan span = new ForegroundColorSpan(Color.parseColor(color));
            ss.setSpan(span, start, end,
                    SpannableString.SPAN_INCLUSIVE_INCLUSIVE);
            view.setText(ss);
        }
    }

    /**
     * 设置TextView中字体颜色 以及下划线
     *
     * @param view
     * @param msg
     * @param start
     * @param end
     * @param color #ea361c
     */
    public static void setForegroundColorAndUnderLineSpan(TextView view, String msg, int start, int end, String color) {
        if (msg.length() > 0) {
            SpannableString ss = new SpannableString(msg);
            ForegroundColorSpan span = new ForegroundColorSpan(Color.parseColor(color));
            UnderlineSpan spanLine = new UnderlineSpan();
            ss.setSpan(spanLine, start, end,
                    SpannableString.SPAN_INCLUSIVE_INCLUSIVE);
            ss.setSpan(span, start, end,
                    SpannableString.SPAN_INCLUSIVE_INCLUSIVE);
            view.setText(ss);
        }
    }

    // 格式化数据保留两位小数
    public static String transData(String money) {
        double mon = 0.00;
        try {
            mon = Double.parseDouble(money);
        } catch (Exception e) {
            mon = 0.00;
        }
        DecimalFormat format = new DecimalFormat("##0.00");
        return format.format(mon);
    }

    /**
     * 计算年龄
     *
     * @param IdNO
     * @return
     */
    public static int IdNOToAge(String IdNO) {
        String dates = "";
        dates = IdNO.substring(6, 10);
        SimpleDateFormat df = new SimpleDateFormat("yyyy");
        String year = df.format(new Date());
        int age = 0;
        try {
            age = Integer.parseInt(year) - Integer.parseInt(dates);
        } catch (Exception e) {
            age = 0;
        }
        return age;
    }

    /**
     * 获取注册时间
     *
     * @param regdate
     * @return
     */
    public static String getRegdate(String regdate) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy");
        String currentYear = df.format(new Date());
        String regdateYear;
        try {
            regdateYear = df.format(df.parse(regdate));
        } catch (ParseException e) {
            regdateYear = df.format(new Date());
        }
        int years = 0;
        try {
            years = Integer.parseInt(currentYear) - Integer.parseInt(regdateYear);
        } catch (Exception e) {
            years = 0;
        }
        return String.valueOf(years < 0 ? 0 : years);
    }


    /**
     * 判断服务器时间是否处于开始时间和结束时间之间
     *
     * @param start_time
     * @param end_time
     * @param service_time
     * @return 抢购中 0 服务器时间介于开始和结束时间之间; 即将开始-1 服务器时间小于开始时间；已结束1 服务器时间大于结束时间
     */
    public static int compareDate(String start_time, String end_time, String service_time) {

        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            Date startTime = format.parse(start_time);
            Date endTime = format.parse(end_time);
            Date serviceTime = format.parse(service_time);//服务器时间

            if (startTime.getTime() <= serviceTime.getTime() && serviceTime.getTime() <= endTime.getTime()) {//处于开始和结束之间
                return 0;
            } else if (serviceTime.getTime() < startTime.getTime()) {
                return -1;
            } else if (serviceTime.getTime() > endTime.getTime()) {
                return 1;
            }
        } catch (ParseException e) {
            return 1;
        }
        return -2;
    }

    /**
     * 时间比大小
     *
     * @param end_time
     * @param service_time
     * @return
     */
    public static int compareDateYMD(String end_time, String service_time) {

        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        if (TextUtils.isEmpty(end_time) || TextUtils.isEmpty(service_time)) {
            return 1;
        }
        try {
            Date endTime = format.parse(end_time);
            Date serviceTime = format.parse(service_time);

            if (serviceTime.getTime() <= endTime.getTime()) {
                return 0;
            }
            return 1;
        } catch (ParseException e) {
            return 1;
        }
    }

    //格式化时间，时间格式为：yyyy-MM-dd hh:ss:mm
    public static Date formatDate(String time) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = format.parse(time);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    //时间格式转换
    public static String transDate2hs(String time) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateFormat formatNew = new SimpleDateFormat("HH:mm");
        try {
            Date date = format.parse(time);
            return formatNew.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }

    //时间格式转换
    public static String transDate2h(String time) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateFormat formatNew = new SimpleDateFormat("HH");
        try {
            Date date = format.parse(time);
            return formatNew.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }

    //时间格式转换
    public static String transDateChinese(String time) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        DateFormat formatNew = new SimpleDateFormat("yyyy年MM日dd");
        try {
            Date date = format.parse(time);
            return formatNew.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取时间戳
     *
     * @param start_time
     * @param service_time
     * @return
     */
    public static long getTimeStamp(String start_time, String service_time) {

        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            Date startTime = format.parse(start_time);
            Date serviceTime = format.parse(service_time);//服务器时间
            return Math.abs(serviceTime.getTime() - startTime.getTime());
        } catch (ParseException e) {
            return 1;
        }
    }

    /**
     * 图片显示在控件左边
     *
     * @param mContext
     * @param tv
     * @param res
     */
    public static void showLeftDrawable(Context mContext, TextView tv, int res, String msg) {
        Drawable dw = mContext.getResources().getDrawable(res);
        dw.setBounds(0, 0, dw.getMinimumWidth(), dw.getMinimumHeight());
        tv.setCompoundDrawables(dw, null, null, null);
        tv.setText(msg);
    }

    /**
     * 图片显示在控件右侧
     *
     * @param mContext
     * @param tv
     * @param res
     * @param msg
     */
    public static void showRightDrawable(Context mContext, TextView tv, int res, String msg) {
        Drawable dw = mContext.getResources().getDrawable(res);
        dw.setBounds(0, 0, dw.getMinimumWidth(), dw.getMinimumHeight());
        tv.setCompoundDrawables(null, null, dw, null);
        tv.setText(msg);
    }

    /**
     * 图片显示在控件左边
     *
     * @param mContext
     * @param tv
     * @param res
     */
    public static void showTopDrawable(Context mContext, TextView tv, int res, String msg) {
        Drawable dw = mContext.getResources().getDrawable(res);
        dw.setBounds(0, 0, dw.getMinimumWidth(), dw.getMinimumHeight());
        tv.setCompoundDrawables(null, dw, null, null);
        tv.setText(msg);
    }

    /**
     * 初始化RecycleView布局方式
     *
     * @param mContext
     * @param recyclerView
     * @param span
     */
    public static void initGridRecycle(Context mContext, RecyclerView recyclerView, int span) {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, span) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(gridLayoutManager);
    }

    /**
     * 单位设置 默认为 斤
     * 控制是否可见
     *
     * @param unit
     * @return
     */
    public static void getUnit(String unit, TextView unitView) {
        unitView.setVisibility(View.GONE);
        String u = "";
        if (TextUtils.isEmpty(unit)) {
            u = "单位(斤)";
        } else {
            u = "单位(" + unit + ")";
        }
        unitView.setText(u);
    }

    /**
     * 单位设置 默认为 斤
     *
     * @param unit
     * @return
     */
    public static String getUnit(String unit) {
        if (TextUtils.isEmpty(unit)) {
            return "斤";
        }
        return unit;
    }

    /**
     * 字符串转为整型
     *
     * @param value
     * @return
     */
    public static int stringToInt(String value) {
        int v = 0;
        try {
            v = Integer.parseInt(value);
        } catch (Exception e) {
            v = 0;
        }
        return v;
    }


    /**
     * 首页：由role 得到keytype
     *
     * @param role
     * @return
     */
    public static String getKeytypeByRole(String role) {
        String keytype = "";
        if (TextUtils.isEmpty(role)) {
            return "18";
        }
        //2地标商家;7特产商家;8粮库商家;9三农供应商
        switch (role) {
            case "2":
                keytype = "4";
                break;
            case "7":
                keytype = "11";
                break;
            case "8":
                keytype = "16";
                break;
            case "9":
                keytype = "24";
                break;
            default:
                break;
        }
        return keytype;
    }

    /**
     * 判断是否为空
     *
     * @param str
     * @return
     */
    public static boolean isNull(String str) {
        return str == null || "".equals(str.trim()) || "null".equals(str);
    }

    /**
     * 判断字符串为null, 返回空串
     *
     * @param str
     * @return
     */
    public static String filterNull(String str) {
        if (isNull(str)) {
            return "";
        }
        return str;
    }


    /**
     * 文本中插入图片
     *
     * @param target
     * @param replace
     * @param mTv
     * @param mContext
     * @param res
     */
    public static void getTextViewImageSpan(String target, String replace, TextView mTv, Context mContext, int res) {
        SpannableStringBuilder builder = new SpannableStringBuilder(target);
        Pattern pattern = Pattern.compile(replace);
        Matcher matcher = pattern.matcher(target);
        while (matcher.find()) {
            builder.setSpan(new ImageSpan(mContext, res), matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        mTv.setText(builder);
    }



public static void showKeyBoard(final EditText ed_phone){
    ed_phone.setFocusable(true);
    ed_phone.setFocusableInTouchMode(true);
    ed_phone.requestFocus();

    Timer timer = new Timer();
    timer.schedule(new TimerTask()
                   {

                       public void run()
                       {
                           InputMethodManager inputManager =
                                   (InputMethodManager)ed_phone.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                           inputManager.showSoftInput(ed_phone, 0);
                       }

                   },
            600);

}

}
